package com.senyint.imsdk.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import org.jivesoftware.smack.packet.Message;

import com.senyint.imsdk.packet.AttachmentPacketExtension;

public class PacketUtil {

	/**
     * 获取jid(user@domain/res)的node值,如user
     * @param jid
     * @return
     */
    public static String getJIDNode(String jid) {
        if(jid == null){
        	return null ;
        }
        int index = jid.indexOf("@");
        if(index > 0){
        	return jid.substring(0,index);
        }
        return jid;
    }
    
    /**
     * 获取jid(user@domain/res)的bare值,如user@domain
     * @param jid
     * @return
     */
    public static String getBareJID(String jid) {
        if(jid == null){
        	return null ;
        }
        int index = jid.indexOf("/");
        if(index > 0){
        	return jid.substring(0,index);
        }
        return jid;
    }
	
	public static boolean isNotMessageEmptyBody(Message message,AttachmentPacketExtension attach){
		return (message.getBody()!=null && message.getBody().trim().length()>0)||attach != null ;
	}
	
	 public static String createConversationID(String user , String participant,String topic){ // throws java.lang.IllegalArgumentException
	    	if(participant == null){
	    		return null ;
	    	}
	    	String[] str = null ;
		 	if(StringUtil.isBlank(topic)){
		 		str = new String[]{user,participant};
		 	}else{
		 		str = new String[]{user,participant,topic};
		 	}
		 	Arrays.sort(str);
		 	StringBuffer sb = new StringBuffer();
		 	for(int i=0;i<str.length;i++){
			  sb.append(str[i]);
		 	}
		 	String result = null ;
			try {
				MessageDigest md5 = MessageDigest.getInstance("MD5");
				byte[] bytes = md5.digest(sb.toString().getBytes());
				result = EncodeUtil.bytes2hexstring(bytes);
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			}
			
	    	return result;
		}
	 
}